package at.codebase.db.dao;

import static at.codebase.db.OfyService.ofy;

import java.util.ArrayList;
import java.util.List;

import at.codebase.core.search.ItemSearch;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EUser;

/**
 * Provides static methods to manage items in the datastore.
 * 
 * @author Daniel Marth <danielmarth@gmx.at>
 */
public class EItemDao {

	static {
		ItemSearch.putItems(getAllItems());
	}
	
	public static void saveAllItems(List<EItem> items) {
		ofy().save().entities(items).now();
		ItemSearch.putItems(items);
	}

	/**
	 * Adds an new Item to the Database
	 * 
	 * ToDo List here:
	 * * Add to Database
	 * * Add to Search Index
	 * 
	 * @param newItem
	 */
	public static void addItem(final EItem itemEntity) {
		ofy().save().entity(itemEntity).now();
		ItemSearch.putItem(itemEntity);
	}
	
	/**
	 * Add or update an EItem from the Database
	 * 
	 * ToDo List here:
	 * * Update Item in the Database
	 * * Update the Search Index
	 * 
	 * @param item
	 */
	public static void saveItem(final EItem itemEntity) {
		ofy().save().entity(itemEntity).now();
		ItemSearch.putItem(itemEntity);
	}

	public static void removeItem(final EItem itemEntity) {
		ItemSearch.removeItem(itemEntity);
		ofy().delete().entity(itemEntity).now();
	}

	public static List<EItem> getAllItems() {
		return ofy().load().type(EItem.class).list();
	}
	
	public static int getItemCount(){
		return ofy().load().type(EItem.class).count();
	}

	public static EItem getItemById(final Long itemId) {
		if(itemId.longValue() <= 0)
			return null;
		return ofy().load().type(EItem.class).filter("itemId", itemId).first()
				.get();
	}
	
	public static List<EItem> getItemsByIds(ArrayList<Long> itemIds) {
		return new ArrayList<EItem>(ofy().load().type(EItem.class).ids(itemIds).values());
	}
	
	public static ArrayList<EItem> getItemsBySeller(final Long userId) {
		return new ArrayList<EItem>(ofy().load().type(EItem.class)
				.filter("seller", EUser.key(userId)).order("-timeCreate")
				.list());
	}
	
	public static List<EItem> getNewestItems(final int count) {
		return ofy().load().type(EItem.class).limit(count).order("-timeCreate").list();
	}

	public static void removeItemsById(ArrayList<Long> itemIds) {
		ItemSearch.removeItems(itemIds);
		ofy().delete().type(EItem.class).ids(itemIds);
	}

}
